/***************************************************************************
 *   threadsafe ring-buffer SDL_RWops test                                 *
 *                                                                         *
 *   Copyright (C) 2004 by Tyler Montbriand                                *
 *   tsm@accesscomm.ca                                                     *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include <stdio.h>
#include <SDL/SDL_thread.h>
#include <SDL/SDL_timer.h>
#include "SDL_rwring.h"

#define STRING "==Hello World=="

int running=1;
int write_thread(void *vrw),read_thread(void *vrw);

int main(int argc, char *argv[])
{
  SDL_Thread *r,*w;
  SDL_RWops *ring=SDL_RWringbuf(256,16,250);

  w=SDL_CreateThread(write_thread,(void *)ring);
  r=SDL_CreateThread(read_thread,(void *)ring);

  fprintf(stderr,"Waiting for 5 seconds, then shutting down.\n");

  SDL_Delay(5000);

  fprintf(stderr,"Shutting down.\n");
  running=0;
  SDL_WaitThread(r,NULL);
  SDL_WaitThread(w,NULL);
  SDL_RWclose(ring);
  return(0);
}

int write_thread(void *vrw)
{
  SDL_RWops *rw=(SDL_RWops *)vrw;
  while(running)
  {
    if(SDL_RWwrite(rw,STRING,16,1)<1)
    {
      fprintf(stderr,"Overflow, quitting\n");
      running=0;
    }
    else
      SDL_Delay(200);
  }

  fprintf(stderr,"write_thread exiting\n");
  return(0);
}

int read_thread(void *vrw)
{
  char buf[20];
  SDL_RWops *rw=(SDL_RWops *)vrw;

  while(SDL_RWread(rw,buf,16,1)==1)
    fprintf(stderr,"Read: %s\n",buf);

  fprintf(stderr,"Underflow\n");
  fprintf(stderr,"read_thread exiting\n");
  return(0);
}
